var listProjects;

function initContent() {
	createList();
	$.getJSON("http://193.147.175.241:8080/restisa/projects", function(data){
		$.each(data, function(i,project){
			addProjectToList(project);
		});			
	});	
}

function createTable() {
	var table = "<table id='table_projects'>";
	table += "<caption>Projects</caption>";
	table += "</table";
	
	var div = "<div id='div_projects'>";
	div += table;
	div += "</div>";
	
	$(div).appendTo("#content");
}

function createList() {
	var list = "<ul id='list_projects'></ul>";

	var div = "<div id='div_projects'>";
	div += list;
	div += "</div>";

	$(div).appendTo("#content");
	
}

function addProjectToTable(project) {
	var element = "<tr>";
	
	element += "<td>";
	var name = project.title.replace(/\s/g, "-");
	element += "<a href='#" + name + "' onclick='printDetailsProject(" + project.projectID + ")'>" + project.title + "</a>";
	element += "</td>";
	
	element += "</tr>";
	
	$(element).appendTo("#table_projects");
	
}

function addProjectToList(project) {
	var url = "<a href='#" + project.acronym + "' onclick='printDetailsProject(" + project.projectID + ")'>" + project.acronym + "</a>";
	
	var li = "<li>";
	li += url;
	li += "</li>";
	
	$(li).appendTo("#list_projects");
}

function printDetailsProject(id) {
	listProjects = $("#div_projects").detach();
	
	$.getJSON("http://193.147.175.241:8080/restisa/projects/" + id, function(project){
		var div = "<div id='details_project'>";
		
		var details = "<ul>";
		details += "<li>Acronym: " + project.acronym + "</li>";
		details += "<li>Title: " + project.title + "</li>";
		var coordinator = project.coordinator.name + " " + project.coordinator.surname
		details += "<li>Coordinator: " + coordinator + "</li>";
		var authors = getAuthors(project);
		details += "<li>Research staff: " + authors + "</li>";
		details += "</ul>";	
		div += details;
		
		div += "</div>";
		
		$(div).appendTo("#content");	
	});	
}

function getAuthors(project) {
	console.log($(project.authors).length);
	var authors = "";
	$.each(project.authors, function(i, author) {
		authors += author.name + " " + author.surname;
		if(i < $(project.authors).length - 1) {
			authors += ", ";
		}
	});
	return authors;
}

	